package com.evaluation_system.controller;

import ch.qos.logback.classic.Logger;
import com.evaluation_system.exception.*;
import com.evaluation_system.pojo.entity.*;
import com.evaluation_system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class UserController {


    private static final Logger LOGGER = (Logger) LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UploadService uploadService;
    @Autowired
    private EvaluatorService evaluatorService;
    @Autowired
    private CheckerService checkerService;


    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> handleUpload(
            @RequestParam("filename") String filename,
            @RequestParam("summary") String summary,
            @RequestPart("file") MultipartFile file,
            @RequestParam("username") String username) {

        Map<String, Object> response =new HashMap<>();
        try {
            response = uploadService.encryptInfo(file, filename);
            uploadService.getUserId( username);
            uploadService.saveFile(filename, summary);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            if(e instanceof fileEncryptFailException){
            LOGGER.info("", e);
            response.put("status", "error");
            response.put("message", "加密失败: ");
            }

            if(e instanceof fileSaveFailException){
                LOGGER.info("", e);
                response.put("status", "error");
                response.put("message", "文件保存失败: " );
            }
        }
        return ResponseEntity.internalServerError().body(response);
    }


    @RequestMapping("/evaluator/list")
    public ResponseEntity<Map<String, Object>> getEvaluatorList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String filename) {

        Map<String, Object> response = new HashMap<>();
        // 1. 调用 Service 查询数据
        try {
            List<saveFileInfo> fileList = evaluatorService.readFile(size,page, filename);

            response.put("code", 200);
            response.put("message", "success");
            response.put("data", fileList);                   // 当前页数据列表/
            response.put("page", page);                       // 当前页码
            response.put("size", size);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            if(e instanceof zeroPageException){
                LOGGER.info("", e);
                response.put("status", "error");
                response.put("message", "页数为0异常: " );
            }
        }

        return ResponseEntity.internalServerError().body(response);
    }

    @RequestMapping("/evaluator/download/{id}")
    public ResponseEntity<Map<String, Object>> downloadPdf(
            @RequestParam("fileId") Integer id
    ) {
        Map<String, Object> response = new HashMap<>();
        // 1. 获取PDF字节数组（示例代码）
        try {
            //从阿里云下载加密后的文件并转换成字节数组
            byte[] pdfBytes = evaluatorService.getDownloadpdf(id);
            // 对字节数组进行解密
            pdfBytes=evaluatorService.decryptionPdf(pdfBytes,id);
            //获取下载的URL
            String downloadUrl=evaluatorService.getDownloadUrl(id,pdfBytes);
            response.put("code", 200);
            response.put("message", "success");
            response.put("url", downloadUrl);
            return ResponseEntity.ok(response);// 当前页数据列表/
        } catch (Exception e) {
            if(e instanceof downloadFailException)
            LOGGER.error("", e);
            response.put("status", "error");
            response.put("message", "下载失败: " + e.getMessage());

            if(e instanceof decryptedFailException){
                LOGGER.error("", e);
                response.put("status", "error");
                response.put("message", "解密失败: " + e.getMessage());
            }
        }
        return ResponseEntity.internalServerError().body(response);
    }

    @RequestMapping("/evaluator/score")
    public ResponseEntity<Map<String, Object>> getScore(
            @RequestParam("file_id") Integer fileId,
            @RequestParam("evaluator_id") Integer evaluatorId,
            @RequestParam("score") Integer score
    ){
        Map<String, Object> response = new HashMap<>();
        try {
            evaluatorService.insertIntoScore(fileId, evaluatorId, score);
            response.put("code", 200);
            response.put("message", "success");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            if(e instanceof paramNullException){
                LOGGER.error("", e);
                response.put("status", "error");
                response.put("message", "参数为空: " + e.getMessage());
            }
            if(e instanceof scoreErrorException){
                LOGGER.error("", e);
                response.put("status", "error");
                response.put("message", "评分不正确: " + e.getMessage());
            }
        }

        return ResponseEntity.internalServerError().body(response);
    }

    @RequestMapping("/checker/list")
    public ResponseEntity<Map<String, Object>> getCheckerList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String filename
    ){
        Map<String, Object> response = new HashMap<>();

        try {
            List<saveFileInfo> fileList = checkerService.readFileForChecker(size,page, filename);
            checkerResult checkRes = new checkerResult(fileList,fileList.size());
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", checkRes);                   // 当前页数据列表/
            response.put("page",page);                       // 当前页码
            response.put("size", size);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            if(e instanceof zeroPageException){
                LOGGER.info("", e);
                response.put("status", "error");
                response.put("message", "页数为0异常: " );
            }
        }

        return ResponseEntity.internalServerError().body(response);
    }

    @RequestMapping("/checker/check")
    public ResponseEntity<Map<String, Object>> postChecker(
            @RequestParam("file_id") Integer fileId,
            @RequestParam("checker_id") Integer checkerId,
            @RequestParam("checked") Integer checked
    ){
        Map<String, Object> response = new HashMap<>();
        try {
            checkerService.updateChecker(fileId, checkerId, checked);
            response.put("message", "success");
            response.put("code", 200);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            LOGGER.info("", e);
            response.put("status", "error");
            response.put("message", "服务器异常: " + e.getMessage());
        }
        return ResponseEntity.internalServerError().body(response);
    }

}
